﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using HYView;

namespace YJKArchMethodLibrary.GradeLevel
{
	public class GradeLevelSearch
	{
		public static Level GetGradeLevel(Document doc)
		{
			return GradeLevelSearch.GetGradeLevel(FloorSelectManager.GetSortLevels(doc, double.MinValue, double.MaxValue));
		}

		private static Level GetGradeLevel(List<Level> levels)
		{
			Level result = null;
			foreach (Level level in levels)
			{
				if (GradeLevelSearch.KeyWordMatch(level.Name))
				{
					result = level;
				}
			}
			int firstFloorLevel = GradeLevelSearch.GetFirstFloorLevel(levels);
			if (firstFloorLevel != -1 && firstFloorLevel != 0)
			{
				Level level2 = levels[firstFloorLevel - 1];
				if (level2.get_Parameter(BuiltInParameter.LEVEL_IS_BUILDING_STORY).AsValueString() == "否")
				{
					result = level2;
				}
			}
			else
			{
				Level level3 = levels[firstFloorLevel + 1];
				if (level3.get_Parameter(BuiltInParameter.LEVEL_IS_BUILDING_STORY).AsValueString() == "否")
				{
					result = level3;
				}
			}
			return result;
		}

		private static int GetFirstFloorLevel(List<Level> levels)
		{
			for (int i = 0; i < levels.Count; i++)
			{
				if (levels[i].Elevation == 0.0)
				{
					return i;
				}
			}
			return -1;
		}

		private static bool KeyWordMatch(string name)
		{
			foreach (string value in GradeLevelSearch.m_LevelKeyWord)
			{
				if (name.Contains(value))
				{
					return true;
				}
			}
			return false;
		}

		private static string[] m_LevelKeyWord = new string[]
		{
			"室外",
			"地坪"
		};
	}
}
